import libtorrent as lt
import time
import sys

def download_torrent(torrent_file, save_path):
    # 创建会话
    ses = lt.session()
    ses.listen_on(6881, 6891)  # 监听端口
    
    # 添加种子文件
    with open(torrent_file, 'rb') as f:
        torrent_data = f.read()
    
    info = lt.torrent_info(lt.bdecode(torrent_data))
    h = ses.add_torrent({'ti': info, 'save_path': save_path})
    
    print(f"开始下载: {info.name()}")
    
    # 显示下载进度
    while not h.is_seed():
        s = h.status()
        
        print(f"\r进度: {s.progress * 100:.2f}% | "
              f"下载速度: {s.download_rate / 1000:.1f} kB/s | "
              f"上传速度: {s.upload_rate / 1000:.1f} kB/s | "
              f"Peers: {s.num_peers}", end=' ')
        
        sys.stdout.flush()
        time.sleep(1)
    
    print(f"\n下载完成: {info.name()}")

if __name__ == "__main__":
    torrent_file = "your_torrent_file.torrent"  # 替换为你的种子文件
    save_path = "./downloads"  # 下载保存路径
    
    download_torrent(torrent_file, save_path)